<template>
  <div>
    <div class="card" style="margin-bottom: 5px;">
        <el-input v-model="data.name" style="width: 300px; margin-right: 10px" placeholder="请输入名称查询"></el-input>
        <el-button type="primary" @click="load">查询</el-button>
        <el-button type="info" style="margin: 0 10px" @click="reset">重置</el-button>
        <el-button type="success" @click="handleAdd()">新增</el-button>
        <el-button type="danger" @click="delBatch">批量删除</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-table :data="data.tableData" stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="昵称" prop="name"></el-table-column>
        <el-table-column label="头像">
          <template #default="scope">
            <el-image :src="scope.row.avatar" style="width: 40px; height: 40px; border-radius: 50%"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="角色" prop="role">
          <template #default="scope">
            <span v-if="scope.row.role === 'ADMIN'">管理员</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="160">
          <template #default="scope">
            <el-button type="danger" round plain @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="card">
      <el-pagination background layout="->, total, prev, pager, next" @current-change="load"
                     v-model:page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total"></el-pagination>
    </div>

    <!-- 新增弹窗 -->
    <el-dialog title="新增管理员" width="40%" draggable="true" v-model="data.formVisible" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="data.form" label-width="100px" style="padding-right: 50px">
        <el-form-item label="头像" prop="avatar">
          <el-upload ref="uploadRef" :action="uploadUrl" list-type="picture" :on-success="handleImgSuccess" :limit="1" :on-exceed="handleExceed">
            <el-button type="primary" round>上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="data.form.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="昵称" prop="name">
          <el-input v-model="data.form.name" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="info" round @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" round @click="add">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import request from "@/utils/request";
import {reactive, ref, onMounted} from "vue";
import {ElMessageBox, ElMessage } from "element-plus";

const data = reactive({
  formVisible: false,
  form: {},
  tableData: [],
  name: null,
  pageNum: 1,
  pageSize: 5,
  total: 0
})

// 文件上传的接口地址
const uploadUrl = import.meta.env.VITE_BASE_URL + '/files/upload'
const uploadRef = ref(null);
// 处理文件上传的钩子
const handleImgSuccess = (res) => {
  data.form.avatar = res.data
}

// 生成UID
const genFileId = () => Math.random().toString(36).substring(7);

// 分页查询
const load = () => {
  request.get('/admin/selectPage',{
    params:{
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name
    }
  }).then(res=>{
    data.tableData = res.data?.list
    data.total = res.data?.total
  })
}

// 删除
const handleDelete = (id) => {
  ElMessageBox.confirm('删除后数据无法恢复，确定要删除该管理员吗？', '确认删除', {type: 'warning'}).then(res =>{
    request.delete('/admin/delete/'+id).then(res=>{
      if(res.code === '200'){
        load()
        ElMessage.success('操作成功')
      }else{
        ElMessage.error(res.msg)
      }
    })
  }).catch((err) => {})
}

// 新增
const handleAdd = () => {
  data.form = {}
  data.formVisible = true
}
// 新增保存
const add = () => {
  request.post('admin/add',data.form).then(res => {
    if(res.code === '200'){
      load()
      ElMessage.success('操作成功')
      data.formVisible = false
    }else{
      ElMessage.error(res.msg)
    }
  })
}

/**
 * 批量删除
 * @param rows
 */
const handleSelectionChange = (rows) => {
  data.ids = rows.map(row => row.id)
}
const delBatch = () => {
  if(!data.ids){
    ElMessage.error('请选择要删除的数据')
  }else{
    ElMessageBox.confirm('删除后无法恢复，确定要删除吗？', '确认删除', {type: "warning"}).then(res => {
      request.delete('/admin/delete-batch' , {data:data.ids}).then(res => {
        if (res.code === '200') {
          load()
          ElMessage.success('操作成功')
        } else {
          ElMessage.error(res.msg)
        }
      })
    }).catch(err => {
    })
  }
}

// 组件挂载
onMounted(() => {
  console.log('Upload component:', uploadRef.value);
});

// 限制上传头像数量
const handleExceed = (files, fileList) => {
  const upload = uploadRef.value;
  if (upload) {
    upload.clearFiles();
    const file = files[0];
    file.uid = genFileId();
    upload.handleStart(file);
  }
}

// 重置
const reset = () => {
  data.name = null
  load()
}

load()
</script>

